package com.fc.backingbeans;

import javax.faces.bean.SessionScoped

import org.apache.log4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.security.authentication.encoding.Md5PasswordEncoder
import org.springframework.stereotype.Component

import com.fc.entities.User
import com.fc.service.RoleService
import com.fc.service.UserService
import com.fc.user.Gender
import com.fc.utils.MessageUtils

@Component("registrationController")
@SessionScoped
public class RegistrationController implements Serializable{
	private Logger log = Logger.getLogger(RegistrationController.class)

	@Autowired private RoleService roleService
	@Autowired private UserService userService
	@Autowired private Md5PasswordEncoder passwordEncoder
	User user = new User();

	void register() {
		try {
			userService.create(user);
			user.roles.add(roleService.getUserRole())
			user.password = passwordEncoder.encodePassword(user.password, "basicsalt")
			userService.save(user)
			MessageUtils.addInfo("registrationGrowl", "Sikeres regisztráció!", "Felhasználóneved: ${user.userName}");
			user = new User();
		} catch (DataIntegrityViolationException divEx) {
			log.error("Sikertelen regisztráció!", divEx);
			MessageUtils.addError("registrationGrowl","Sikertelen regisztráció!", "A megadott felhasználónév már foglalt.");
		} 
		catch (Exception e) {
			log.fatal("Sikertelen regisztráció!", e);
			MessageUtils.addError("registrationGrowl","Sikertelen regisztráció!", null);
		}
	}
	
	void reset() {
		user = new User()
	}
}
